from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from Ten_times.utils.pagination import StandardResultPagination
from splits.models import Spit
from splits.serializers import SplitSerializer


class SpitView(ModelViewSet):
    '''吐槽列表'''
    serializer_class = SplitSerializer
    queryset = Spit.objects.all()
    pagination_class = None
    lookup_value_regex = '\d+'

    def perform_authentication(self, request):
        """跳过认证过程"""
        pass

    def get_queryset(self):

        # 认证
        # try:
        #     user = self.request.user
        # except Exception as e:
        #     user = None
        #
        # 如果客户端没传Authorization: jwt token
        # 匿名用户对象

        # if user and user.is_authenticated:
        #     # 登录用户
        #     pass
        # else:
        #     # 非登录用户
        #     pass

        spits = Spit.objects.all().order_by('-thumbup')
        for spit in spits:
            try:
                user = spit.user
                user_id = user.id
                spit.nickname = user.nickname
                spit.avatar = user.avatar
                redis_conn = get_redis_connection('split')
                set = redis_conn.smembers('split_col_%s' % user_id)  # 是否收藏
                tset = redis_conn.smembers('split_thu_%s' % user_id)  # 是否点赞
                if set:
                    spit.collect = True
                if tset:
                    spit.hasthumbup = True
            except:
                spit.nickname = None
                spit.avatar = None
        return spits

    def create(self, request, *args, **kwargs):
        parent = request.data.get('parent')
        if parent:
            spit = Spit.objects.get(id=parent)
            serializer = self.get_serializer(data=request.data)
            spit.comment += 1
            spit.save()
            serializer.is_valid()
            serializer.save()
            return Response(serializer.data)
        else:
            if request.user.is_authenticated:
                try:
                    user = request.user
                    request.data['nickname'] = user.nickname
                    request.data['avatar'] = user.avatar
                except:
                    request.data['nickname'] = None
                    request.data['avatar'] = None
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid()
            serializer.save()
            return Response(serializer.data)


class CollectView(APIView):
    '''收藏或取消收藏'''
    permission_classes = [IsAuthenticated]

    def put(self, request, pk):
        user_id = request.user.id
        redis_conn = get_redis_connection('splits')
        set = redis_conn.smembers('split_col_%s' % user_id)
        if pk in set:
            redis_conn.srem('split_col_%s' % user_id, pk)
            return Response({
                "success": 'true',
                "message": "取消收藏"
            })

        else:
            redis_conn.sadd('split_col_%s' % user_id, pk)
            return Response({
                "success": 'true',
                "message": "收藏成功"
            })


class ThumbupView(APIView):
    '''点赞或取消点赞'''
    permission_classes = [IsAuthenticated]

    def put(self, request, pk):
        spit = Spit.objects.get(id=pk)
        user_id = request.user.id
        redis_conn = get_redis_connection('splits')
        tset = redis_conn.smembers('split_thu_%s' % user_id)
        if pk in tset:
            redis_conn.srem('split_thu_%s' % user_id, pk)
            # 点赞量 -1
            spit.thumbup -= 1
            spit.save()
            return Response({
                "success": 'true',
                "message": "取消点赞"
            })
        else:
            redis_conn.sadd('split_thu_%s' % user_id, pk)
            # 点赞量 +1
            spit.thumbup += 1
            spit.save()
            return Response({
                "success": 'true',
                "message": "点赞成功"
            })


class ContentView(APIView):
    def perform_authentication(self, request):
        """跳过认证过程"""
        pass
    # permission_classes = [IsAuthenticated]
    def get(self, request, pk):
        spits = Spit.objects.filter(parent=pk)
        serializer = SplitSerializer(spits, many=True)
        return Response(serializer.data)
